package com.chennan.book.domain.imports;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.CellExtra;
import com.alibaba.excel.util.ListUtils;
import com.chennan.book.domain.model.ExcelFeishuiModel;
import com.chennan.excelpoi.model.CardMoadl;
import com.chennan.excelpoi.model.CardProperty;
import com.chennan.excelpoi.service.CardImportService;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author chennan
 * @create 2022-09
 */
@Slf4j
public class AnhFeiSuiImport extends AnalysisEventListener<Map<Integer, String>> {

    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<ExcelFeishuiModel> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);

    private CardImportService cardImportService;

    public static StringBuilder sb = new StringBuilder();

    public AnhFeiSuiImport(CardImportService cardImportService){
        this.cardImportService = cardImportService;
    }

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
 
    }

    @Override
    public void invoke(Map<Integer, String> integerStringMap, AnalysisContext analysisContext) {
//        log.info("解析到一条数据:{}", JSON.toJSONString(integerStringMap));
        Integer rowIndex = analysisContext.readRowHolder().getRowIndex();
        String sheetName = analysisContext.readSheetHolder().getSheetName();
        int size = integerStringMap.size();
        ExcelFeishuiModel properties = new ExcelFeishuiModel();
        properties.setId(UUID.randomUUID());
        for (int i = 0; i < size; i++) {
            String s = integerStringMap.get(i);
            switch (i){
                case 0:
                    properties.setAdm_div_code(s);
                    break;
                case 1:
                    properties.setAdm_div_name(s);
                    break;
                case 2:
                    properties.setChg_agen_code(s);
                    break;
                case 3:
                    properties.setChg_agen_name(s);
                    break;
                case 4:
                    properties.setPay_code(s);
                    break;
                case 5:
                    properties.setPayer_name(s);
                    break;
                case 6:
                    properties.setAmt(s);
                    break;
                case 7:
                    properties.setPay_time(s);
                    break;
                case 8:
                    properties.setPay_info(s);
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + i);
            }
        }
        cachedDataList.add(properties);
        if (cachedDataList.size() >= BATCH_COUNT) {
            saveData();
            cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
        }
    }
    @Override
    public void extra(CellExtra extra, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        saveData();
        log.info("所有数据解析完成！"+sb);
        try {
            dataWrite("D:\\Work\\aliyunJenkins\\Book\\inset2.sql",sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 写入数据
     * @param filePath
     * @param data
     * @throws IOException
     */
    public void dataWrite(String filePath, String data) throws IOException {
        File file = new File(filePath);
        if(file.exists()&&file.isFile()){
            FileWriter fileWriter = new FileWriter(file);
            fileWriter.write(data);
            fileWriter.flush();
            fileWriter.close();
        }
    }
//    @Override
//    public boolean hasNext(AnalysisContext context) {
//        return false;
//    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        cachedDataList.forEach(item->{
            try {
                sb.append(item.generateSql());
            } catch (ParseException e) {
                e.printStackTrace();
            }
        });
    }

}
